<template>
  <el-dialog
    v-model="dialogImportExcel.visible"
    :title="dialogImportExcel.title"
    draggable
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    close-icon="CloseBold"
    @close="closeDialog"
  >
    <div class="app-container">
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" :rules="rules">
          <el-form-item label="选择文件" prop="fileName">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :show-file-list="false"
              class="upload-demo"
              style="padding-top: 4px"
              :action="actionUrl"
              multiple
              :headers="headers"
              :auto-upload="false"
              :on-error="handleError"
              :on-success="handleSuccess"
              :on-change="handleChange"
              :limit="1"
              :accept="'.xlsx, .xls'"
              :on-exceed="handleExceed"
            >
              <el-row>
                <el-col :span="mobile === 'mobile' ? itemSpan : '22'">
                  <el-input
                    v-model="queryParams.fileName"
                    placeholder="请选择文件"
                    clearable
                    readonly
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="mobile === 'mobile' ? itemSpan : '2'">
                  <el-button type="success" style="margin-left: 10px" :loading="loading" @click="uploadFile">
                    <i-ep-upload />
                    导入 Excel
                  </el-button>
                </el-col>
              </el-row>
              <template #tip>
                <div class="el-upload__tip text-red">限制上传单文件，格式.xlsx, .xls</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between">
            <div></div>
          </div>
        </template>
        <el-form ref="formRef" v-loading="loading" :model="payrollDetailImportFormData">
          <el-table v-loading="loading" :data="payrollDetailImportFormData" border :style="{ height: tableHeight }">
            <el-table-column label="序号" type="index" min-width="60" align="center"></el-table-column>
            <el-table-column key="status" label="状态" align="center" width="60" prop="status">
              <template #default="scope">
                <el-tag v-if="scope.row.status === true" type="success">正确</el-tag>
                <el-tag v-else type="info">错误</el-tag>
              </template>
            </el-table-column>
            <el-table-column key="errorCount" label="错误数" min-width="60" align="center" prop="errorCount" />
            <el-table-column key="errorMsg" label="错误消息" min-width="120" align="center" prop="errorCount" />
            <!-- <el-table-column key="projectName" label="项目名称"  min-width="120" align="center" prop="projectName" /> -->
            <el-table-column key="groupName" label="劳务班组" min-width="60" align="center" prop="groupName" />
            <el-table-column key="personName" label="人员姓名" min-width="80" align="center" prop="personName" />
            <el-table-column key="idCard" label="身份证号" min-width="120" align="center" prop="idCard" />
            <el-table-column key="bankName" label="开户行" min-width="120" align="center" prop="bankName" />
            <el-table-column key="personBankNo" label="银行卡号" min-width="120" align="center" prop="personBankNo" />
            <el-table-column
              key="attendanceDays"
              label="实际考勤天数"
              min-width="80"
              align="center"
              prop="attendanceDays"
            />
            <el-table-column
              key="amountApplied"
              property="amountApplied"
              label="申请发放金额"
              min-width="120"
              prop="amountApplied"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.amountApplied"
                  type="number"
                  controls-position="right"
                  style="width: 100px"
                  class="inputClass"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="100">
              <template #default="scope">
                <el-button type="primary" link size="small" @click="handleDelete(scope.$index)">
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-card>
    </div>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="submitloading" @click="handleSubmit">保存并提交 </el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useUserStore } from "@/store/modules/user";
import type { UploadUserFile, UploadFiles, UploadFile } from "element-plus";
import { useScreen } from "@/store/modules/screen";
import { PayrollDetailEditForm } from "@/api/wage/types";
import { AddPayrollDetail, SubmitPayroll } from "@/api/wage/index";

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(1500);
const tableHeight = computed(() => {
  if (screenStore.screenHeight - 117 - 180 - 60 < 360) {
    return 360;
  } else {
    return screenStore.screenHeight - 117 - 180 - 60;
  }
});
const itemSpan = ref(12);

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 1500;
    itemSpan.value = 12;
  }
}

const useUser = useUserStore();
let props = defineProps({
  dialogImportExcel: {
    type: Object,
    default: () => ({
      visible: false,
      title: "导入",
      id: 0,
      footBtn: "提交",
    }),
  },
});
const { dialogImportExcel } = toRefs(props);
const queryParams = reactive({
  fileName: "",
});
const fileList = ref<UploadUserFile[]>([]);
const uploadRef = ref();
const formRef = ref();
const queryFormRef = ref();
const loading = ref(false);
const submitloading = ref(false);
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/manager/payroll/import`);
const payrollDetailImportFormData = ref<PayrollDetailEditForm[]>();
let headers = ref({
  Authorization: useUser.token,
});
const rules = {
  fileName: [
    {
      required: true,
      trigger: "change",
      validator: fileNameBlur,
    },
  ],
};

function fileNameBlur(rule: any, value: any, callback: any) {
  if (!value || value === undefined || value === "") {
    callback(new Error("文件不能为空"));
    return;
  } else {
    let temp = value.split(".");
    if (temp[temp.length - 1] == "xlsx" || temp[temp.length - 1] == "xls") {
      callback();
    } else {
      callback(new Error("请上传指定文件格式！"));
    }
  }
}

const emit = defineEmits(["sendClose"]);

watch(
  () => dialogImportExcel.value.visible,
  () => {
    if (dialogImportExcel.value.visible) {
      resetForm();
    }
  }
);

onMounted(async () => {
  initScreen();
});

function handleSubmit() {
  submitloading.value = true;
  if (payrollDetailImportFormData.value === undefined) {
    ElMessage.warning("请先导入数据");
    submitloading.value = false;
    return;
  }

  AddPayrollDetail(dialogImportExcel.value.id, payrollDetailImportFormData.value).then((resp) => {
    if (resp.success === true) {
      // ElMessage.success(resp.msg);
      ElMessageBox.confirm("工资单导入成功，是否需要提交?", "提交提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // alert(1);
          // ElMessage.success('成功');

          SubmitPayroll(dialogImportExcel.value.id).then((res) => {
            if (res.success === true) {
              ElMessage.success(res.msg);
              setTimeout(() => {
                closeDialog(true);
                resetForm();
                submitloading.value = false;
              }, 1000);
            } else {
              ElMessage.warning(res.msg);
              setTimeout(() => {
                closeDialog(true);
                resetForm();
                submitloading.value = false;
              }, 1000);
            }
          });
        })
        .catch(() => {
          closeDialog(true);
          resetForm();
          submitloading.value = false;
        });
    } else {
      ElMessage.warning(resp.msg);
      submitloading.value = false;
    }
  });
}

/**
 * 重置表单
 */
function resetForm() {
  payrollDetailImportFormData.value = [];
}

/* 上传超限 */
const handleExceed = (files: File[], uploadFiles: UploadUserFile[]) => {
  const file = files[0];
  uploadRef.value!.handleStart(file);
};

/* 上传成功 */
function handleSuccess(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) {
  if (!response.success) {
    ElMessage.error(response.msg);
    uploadRef.value!.clearFiles();
    loading.value = false;
    return;
  }
  payrollDetailImportFormData.value = response.data;
  uploadRef.value!.clearFiles();
  loading.value = false;
}

/* 文件改变 */
function handleChange(uploadFile: UploadFile, uploadFiles: UploadFiles) {
  fileList.value = [];
  fileList.value.push(uploadFile);
  queryParams.fileName = uploadFile.name;
}

/*上传失败*/
function handleError(error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) {
  ElMessage.error(error);
  uploadRef.value!.clearFiles();
  loading.value = false;
}

function sendIntoClose(refresh: boolean) {
  emit("sendClose", refresh);
}

/* 导入 */
function uploadFile() {
  queryFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      uploadRef.value!.submit();
    }
  });
}

/* 删除 */
function handleDelete(index: number) {
  payrollDetailImportFormData.value?.splice(index, 1); //对tableData中的数据删除一行
}

function closeDialog(refresh: boolean) {
  sendIntoClose(refresh);
}
</script>

<style lang="less" scoped>
.app-container {
  padding: 0px;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.text-red {
  color: red;
}
</style>
